<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区 -->
    <el-card>
      <el-row>
        <el-col>
          <el-alert
            title="注意:只允许为三级分类设置相关参数"
            type="warning"
            show-icon
          >
          </el-alert>
        </el-col>
      </el-row>
      <!-- 下拉框选择商品分类 -->
      <el-row class="mt">
        <el-col>
          选择商品分类:
          <!-- options是数据源需要请求后台得到 v-model绑定的是下拉选中后得到的数字的id props配置项 -->
          <el-cascader
            clearable
            v-model="checkedvalue"
            :options="datalist"
            :props="cascaderprops"
            @change="handleChange"
          ></el-cascader>
        </el-col>
      </el-row>
      <!-- tabs面板 -->
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <!-- 动态参数部分 -->
        <el-tab-pane label="动态参数" name="many">
          <el-button :disabled="siDisable" @click="addbtn = true"
            >添加参数</el-button
          >
          <!-- 添加参数的表格 -->
          <el-table :data="many" style="width: 100%">
            <el-table-column type="expand">
              <template v-slot="{ row }">
                <span class="m" v-for="(item, i) in row.attr_vals" :key="i">
                  <el-tag @close="delclose(i, row)" closable>{{ item }}</el-tag>
                </span>
                <!-- 添加tag标签 -->
                <el-input
                  class="input-new-tag"
                  v-if="row.inputVisible"
                  v-model="row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(row)"
                  @blur="handleInputConfirm(row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index"> </el-table-column>
            <el-table-column prop="attr_name" label="名称"> </el-table-column>
            <el-table-column label="操作">
              <template v-slot="{ row }">
                {{ row.attr_id }}
                <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  @click="editbtn(row)"
                  >编辑</el-button
                >
                <el-button
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  @click="delbtn(row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 静态属性部分 -->
        <el-tab-pane label="静态属性" name="only">
          <el-button :disabled="siDisable" @click="addbtn = true"
            >添加属性</el-button
          >
          <!-- 添加属性的表格 -->
          <el-table :data="only" style="width: 100%">
            <el-table-column type="expand">
              <template v-slot="{ row }">
                <span class="m" v-for="(item, i) in row.attr_vals" :key="i">
                  <el-tag delclose closable>{{ item }}</el-tag>
                </span>
                <!-- 添加tag标签 -->
                <el-input
                  class="input-new-tag"
                  v-if="row.inputVisible"
                  v-model="row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(row)"
                  @blur="handleInputConfirm(row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index"> </el-table-column>
            <el-table-column prop="attr_name" label="名称"> </el-table-column>
            <el-table-column label="操作">
              <template v-slot="{ row }">
                {{ row.attr_id }}
                <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  @click="editbtn(row)"
                  >编辑</el-button
                >
                <el-button
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  @click="delbtn(row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
      <!-- 添加参数和属性的对话框 -->
      <el-dialog
        :title="str + text"
        :visible.sync="addbtn"
        width="30%"
        @close="addclose"
      >
        <!-- 添加参数和属性的表单 -->
        <span>
          <el-form
            :model="addForm"
            :rules="addrules"
            ref="addruleForm"
            label-width="100px"
          >
            <el-form-item :label="text" prop="attr_name">
              <el-input v-model="addForm.attr_name"></el-input>
            </el-form-item>
          </el-form>
        </span>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addbtn = false">取 消</el-button>
          <el-button type="primary" @click="addyes">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  name: '',
  data() {
    return {
      // 下拉菜单选择项的数组
      checkedvalue: [],
      // 数据源
      datalist: [],
      // props项
      cascaderprops: {
        //鼠标经过触发
        expandTrigger: 'hover',
        //展示用户看到的字段
        label: 'cat_name',
        // 父子关联节点
        children: 'children',
        // 提交的数据,选id的话下拉菜单选择项的数组中存的就是id
        value: 'cat_id'
      },
      // 切换面板时触发活动状态是only还是many
      activeName: 'many',
      // only的数据
      only: [],
      // many 的数据
      many: [],
      // 弹出添加对话框按钮
      addbtn: false,
      // 添加参数和属性的参数
      addForm: {
        attr_name: ''
      },
      // 验证表单规则
      addrules: {
        attr_name: [
          { required: true, message: '请输入活动名称', trigger: 'blur' }
        ]
      },
      // 开关变量
      str: '添加',
      // 开关变量
      flag: true
    }
  },
  created() {
    this.getlist()
  },
  // mounted () {},
  computed: {},
  watch: {},
  methods: {
    // 拉下菜单变化触发
    handleChange() {
      // console.log(this.checkedvalue.length);

      this.getattr()
    },
    //获取数据给data
    async getlist() {
      //获取数据并赋值给data
      const { data: res } = await this.$http.get(`categories`)
      if (res.meta.status !== 200) {
        return this.$message.error('获取用户列表失败！')
      } //赋值data中定义的数据
      this.datalist = res.data
    },
    //切换面板时触发
    handleClick() {
      this.getattr()
    },
    //定义获取动态参数和静态属性的方法
    async getattr() {
      if (this.checkedvalue.length !== 3) {
        return (this.checkedvalue = [])
      }
      const {
        data: res
      } = await this.$http.get(
        `categories/${this.checkedvalue[2]}/attributes`,
        { params: { sel: this.activeName } }
      )

      if (res.meta.status !== 200) {
        return this.$message.error('获取用户列表失败！')
      }
      // if (this.activeName == "only") {
      //   this.only = res.data;
      // } else {
      //   this.many = res.data;
      // }
      //把请求来的字符串atte_vals转换成数组后期容易操纵
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals.length ? item.attr_vals.split(' ') : []
        // 定义自己的属性,不共用data中的数据
        // 控制tag标签的显示隐藏
        item.inputVisible = false
        // tag标签的双向绑定值
        item.inputValue = ''
      })
      // console.log(res.data);
      this.activeName == 'only'
        ? (this.only = res.data)
        : (this.many = res.data)
    },
    addclose() {
      this.$refs.addruleForm.resetFields()
    },
    // 确定添加和确定修改合并
    addyes() {
      if (this.flag == true) {
        // 表单验证通过才允许发送请求减轻服务器压力
        this.$refs.addruleForm.validate(async valid => {
          if (!valid) return // 可以发起添加用户的网络请求 注意addForm是data中定义的其值和表单双向绑定的对象
          const { data: res } = await this.$http.post(
            `categories/${this.checkedvalue[2]}/attributes`,
            {
              attr_name: this.addForm.attr_name,
              attr_sel: this.activeName
            }
          )
          if (res.meta.status !== 201) {
            return this.$message.error('添加用户失败！')
          }
          this.$message.success('添加用户成功！') // 隐藏添加用户的对话框???
          this.addbtn = false // 重新获取用户列表数据
          this.getattr()
        })
      } else {
        // 确定修改
        this.$refs.addruleForm.validate(async valid => {
          if (!valid) return // 可以发起添加用户的网络请求 注意addForm是data中定义的其值和表单双向绑定的对象
          const { data: res } = await this.$http.put(
            `categories/${this.checkedvalue[2]}/attributes/${this.addForm.attr_id}`,
            {
              attr_name: this.addForm.attr_name,
              attr_sel: this.addForm.attr_sel,
              attr_vals: this.addForm.attr_vals ? this.addForm.attr_vals : ''
            }
          ) // console.log(res);
          if (res.meta.status !== 200) {
            return this.$message.error('更改用户失败！')
          }
          this.$message.success('更改用户成功！') // 隐藏添加用户的对话框???
          this.addbtn = false // 重新获取用户列表数据
          this.getattr() //刷新列表
          this.flag = true //开关重置
          this.str = '添加' //标签重置
          this.addForm.attr_name = '' //表单内容重置
        })
      }
    },
    // 点击按钮删除
    async delbtn(row) {
      // 弹框询问用户是否删除数据
      const confirmResult = await this.$confirm(
        '此操作将永久删除该用户, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err) // 如果用户确认删除，则返回值为字符串 confirm // 如果用户取消了删除，则返回值为字符串 cancel // console.log(confirmResult)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      const { data: res } = await this.$http.delete(
        `categories/${this.checkedvalue[2]}/attributes/${row.attr_id}`
      )
      if (res.meta.status !== 200) {
        return this.$message.error('删除用户失败！')
      }
      this.$message.success('删除用户成功！')
      this.getattr()
    },
    // 点击修改按钮弹出对话框
    editbtn(row) {
      this.str = '修改'
      this.flag = false
      this.addForm = row
      this.addbtn = true
    },
    // 失去焦点触发提交tag事件
    async handleInputConfirm(row) {
      // 非空验证
      if (!row.inputValue.trim()) {
        row.inputValue = ''
        row.inputVisible = false
        return
      }
      // 把数据push到row中
      row.attr_vals.push(row.inputValue.trim())
      // row里面是最新的值,可以发请求了
      this.gettag(row)
      // 关框
      row.inputVisible = false
      // 清数据
      row.inputValue = ''
    },
    // 点击出现tag标签输入框
    showInput(row) {
      row.inputVisible = true
      // 聚焦光标方法
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 定义获取最新数据渲染tag标签
    async gettag(row) {
      const { data: res } = await this.$http.put(
        `categories/${this.checkedvalue[2]}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: this.activeName,
          attr_vals: row.attr_vals.join(' ')
        }
      )
      // console.log(res);
      if (res.meta.status !== 200) {
        return this.$message.info('失败')
      }
      return this.$message.success('成功')
    },
    // 点击叉号利用下标删除tag标签
    delclose(i, row) {
      // 删除索引第i项的那个数组成员
      row.attr_vals.splice(i, 1)
      // 调用重新渲染方法
      this.gettag(row)
    }
  },
  // 计算禁用按钮属性
  computed: {
    siDisable() {
      if (this.checkedvalue.length == 3) return false
      return true
    },
    text() {
      if (this.activeName == 'many') return '动态参数'
      return '静态属性'
    }
  }
}
</script>

<style lang="less" scoped>
.mt {
  margin-top: 15px;
}
.m {
  margin: 10px;
}
.input-new-tag {
  width: 120px;
}
</style>
